package org.example.config;

import org.example.datasource.DynamicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Component
public class DynamcDataSourceReplacerRunner implements ApplicationRunner {

    @Autowired
    private ConfigurableApplicationContext context;

    @Autowired
    @Qualifier("shardingMaster")
    private DataSource shardingMaster;
    @Autowired
    @Qualifier("physicalMaster")
    private DataSource physicalMaster;
    @Autowired
    @Qualifier("pgDataSource")
    private DataSource pgDataSource;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        DataSource bean = context.getBean(DataSource.class);
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        String dynamicDataSourceName = "dynamicDataSource";
        beanFactory.destroyBean(dynamicDataSourceName, bean);
        beanFactory.destroyBean(bean);
        if (beanFactory instanceof DefaultListableBeanFactory) {
            DefaultListableBeanFactory listableBeanFactory = (DefaultListableBeanFactory) beanFactory;
            BeanDefinition dynamicDataSourceDef = listableBeanFactory.getBeanDefinition(dynamicDataSourceName);
            listableBeanFactory.removeBeanDefinition(dynamicDataSourceName);
            System.out.println(beanFactory.containsBean(dynamicDataSourceName));
            DynamicDataSource dynamicDataSource = new DynamicDataSource();
            // 添加所有数据源
//        dynamicDataSource.addDataSource("slaveDataSource", slaveDataSource);
            dynamicDataSource.addDataSource("shardingMaster", shardingMaster);
            dynamicDataSource.addDataSource("physicalMaster", physicalMaster);
            dynamicDataSource.addDataSource("pgDataSource", pgDataSource);
            // 设置默认数据源
            dynamicDataSource.setDefaultTargetDataSource(physicalMaster);
            listableBeanFactory.registerBeanDefinition(dynamicDataSourceName, dynamicDataSourceDef);
            beanFactory.registerSingleton(dynamicDataSourceName, dynamicDataSource);
            beanFactory.getBeanDefinition(dynamicDataSourceName).setPrimary(true);
        }
    }
}
